//
//  MessageTextField.m
//  ABlip
//
//  Created by dawid on 09-01-04.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MessageTextField.h"
#import "AppController.h"
#import "RegexKitLite.h"

@implementation MessageTextField
@synthesize draggedImagePath;
@synthesize attView;
#define fontColor 0.25098
#define borderColor 0.5725
#define direct_regex @"^\\s*>{1,2}\\s*(\\S+)?$"
#define mentioned_user_regex @".*\\^\\s*(\\S+)?"
#define recipient_regex @"^\\s*>{1,2}\\s*(\\S+)"
#define direct_regex_only_start @"^\\s*>{1,2}"

-(void)awakeFromNib
{
	[self registerForDraggedTypes:
	 [NSArray arrayWithObjects:NSFilenamesPboardType, NSPICTPboardType, NSStringPboardType,nil]];

	
	[self setTypingAttributes:[MessageTextField attributesDefault]];
	[self setTextContainerInset:NSMakeSize(4, 4)];
	//[self setDelegate:self];
//	[self 
}
- (NSArray *)readablePasteboardTypes
{
	return [NSArray arrayWithObjects:  NSPICTPboardType,NSStringPboardType,nil];
}
- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard type:(NSString *)type
{
	if (type !=nil && [type isEqualToString:NSPICTPboardType]){
		[self setDraggedImagePath:IMAGE_PASTED_NAME];
		NSData *data = [pboard dataForType:type];
		if (data){
			//[[self attView] setImageData:data];
			NSString *path = [NSString stringWithString: [[AppController appSupportDir] stringByAppendingPathComponent:IMAGE_PASTED_NAME]];
			NSImage* img = [[NSImage alloc] initWithData:data];
			data = [img TIFFRepresentation];
			[data writeToFile:path atomically:YES];
			[self setDraggedImagePath:path];
			if (img){
				[img release];
				img = nil;
			}
		} else {
			[self setDraggedImagePath:@""];
		}
		return NO;
	} else {
		return [super readSelectionFromPasteboard:pboard type:type];
	}
	
	
}
-(void)dealloc
{
	if (draggedImagePath){
		[draggedImagePath release];
		draggedImagePath = nil;
	}
	if (attView){
		[attView release];
		attView = nil;
	}
	[super dealloc];
}
-(void)deleteAttPicture:(NSNotification*)note
{

	if (attView == nil)
		return;

	[attView removeFromSuperview];
	attView = nil;
	[self setNeedsDisplay:YES];
	
}
-(void)setDraggedImagePath:(NSString*)value
{
	if (value == nil){
#ifdef __DEBUG__

		NSLog(@"value= nil");

#endif
	} else	if ([value isEqualToString:@""]){
		[self deleteAttPicture:nil];
		draggedImagePath = @"";
		return;
	}
	if ([[value pathExtension] isMatchedByRegex:IMAGE_EXTENSIONS]==NO)
		return;
		
	[value retain];
	[draggedImagePath release];
	
	draggedImagePath = value;

		if (attView ==nil){
			attView = [[AttachedPictureView alloc] initWithFrame:NSMakeRect(263 , 37, 88, 27)];
			
			[attView setPictureName:[draggedImagePath lastPathComponent]];
			[[AppController shared] addAttachmentToBox];
			//[self addSubview:attView];
			[attView release];
		}
		else {
			[attView setPictureName:[draggedImagePath lastPathComponent]];
		}
	
	
}
-(void)addQuote:(NSString*)quote 
{
	NSRange r = [self selectedRange];
	NSString *prev = [[self string] substringToIndex:r.location];
	NSString *from  =[[self string] substringFromIndex: r.location];
	[self setString:[NSString stringWithFormat:@"%@%@ %@", prev, quote, from]];
}
#pragma mark userNames_hints
-(NSArray *)completionsForPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index
{
	

	NSString *stringToComplete = [self string];
  NSRange userRange = [stringToComplete rangeOfRegex:direct_regex];
	
	if (charRange.location >= userRange.location &&
		charRange.location <= userRange.location + userRange.length){
		NSString* userPartName = [stringToComplete substringWithRange:charRange];
		userPartName = [userPartName stringByReplacingOccurrencesOfString:@">"withString:@""];
		userPartName = [userPartName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
		userPartName = [userPartName lowercaseString];
		if ([userPartName length] ==0)
			return [[AppController shared] userNames];

		NSPredicate * predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat: @"SELF BEGINSWITH '%@'", userPartName]];
		return [[[AppController shared] userNames] filteredArrayUsingPredicate:predicate]; 
		
	}
	else {
		userRange = [stringToComplete rangeOfRegex:mentioned_user_regex];
		if (charRange.location >= userRange.location &&
			charRange.location <= userRange.location + userRange.length){
			NSString* userPartName = [stringToComplete substringWithRange:charRange];
			userPartName = [userPartName stringByReplacingOccurrencesOfString:@"^"withString:@""];
			userPartName = [userPartName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
			userPartName = [userPartName lowercaseString];
			if ([userPartName length] ==0)
				return [[AppController shared] userNames];
			
			NSPredicate * predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat: @"SELF BEGINSWITH '%@'", userPartName]];
			return [[[AppController shared] userNames] filteredArrayUsingPredicate:predicate]; 
		}	
		
		[super completionsForPartialWordRange:charRange indexOfSelectedItem:index];
	}
	return nil;
}
- (void)insertCompletion:(NSString *)word forPartialWordRange:(NSRange)charRange movement:(NSInteger)movement isFinal:(BOOL)flag
{
	if (movement == NSReturnTextMovement ||
		movement == NSTabTextMovement){
		word = [NSString stringWithFormat:@"%@ ", word];
		NSString *changingString = [[self string] substringWithRange:charRange];
		if ([changingString isMatchedByRegex:@">{1,2}"] == YES){
			[self setString:[[self string] stringByReplacingCharactersInRange:NSMakeRange(charRange.location+1, charRange.length-1) withString:word]];
		}else {
			[self setString:[[self string] stringByReplacingCharactersInRange:charRange withString:word]];
		}
		
		
	}
}
-(void)changeMessageToType
{
	NSString *stringToComplete = [self string ];
	NSRange dirSignRange  = [stringToComplete rangeOfRegex:direct_regex_only_start];

	if (dirSignRange.length >0){
		if (dirSignRange.length == 1)
			[self setString:[[self string] stringByReplacingCharactersInRange:NSMakeRange(dirSignRange.location, dirSignRange.length) withString:@">>"]];
		else {
			[self setString:[[self string] stringByReplacingCharactersInRange:NSMakeRange(dirSignRange.location, dirSignRange.length) withString:@">"]];
		}

	}
}

-(BOOL)acceptsFirstResponder
{
	return YES;
}

- (void)keyDown:(NSEvent *)event
{
	if ([self isEditable] == NO)
		return;
	int length = [[self stringValue] length];
	if ([event keyCode]==36)
	{
		[self setStringValue:[[self stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
		if (length <= 160){
			NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
			[nc postNotificationName:ABL_SendMessageNotification object:self];
			
			
		}
	}else {
		 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
		length = [[self stringValue] length];
		[[self textStorage] setAttributes:[[self class] attributesDefault] range:NSMakeRange(0,  length)];
		if (length > 160){
			@try{
				[[self textStorage] setAttributes:[[self class] attributeRedLetters] range:NSMakeRange(160, length - 160)];
			}
			@catch (NSException *ex) {
#ifdef __DEBUG__

				NSLog(@"Błąd w zmianie koloru tekstu");

#endif
			}
			
		}
		NSRange r = [self rangeForUserTextChange];
		NSString* checkString = [[self stringValue] substringWithRange:NSMakeRange(0, r.location)];
#ifdef __DEBUG__

		NSLog(@"check = %@", checkString);

#endif
		NSRange userRange  = [checkString rangeOfRegex:direct_regex];
		if (r.location >= userRange.location &&
			r.location <= userRange.location + userRange.length){

			[self complete:self];
		} else {
			userRange  = [checkString rangeOfRegex:mentioned_user_regex];
			if (r.location >= userRange.location &&
				r.location <= userRange.location + userRange.length){
				[self complete:self];
			}
		}

	}
	
	
}
-(void)markNotExistedRecipient
{
	NSRange r = [[self stringValue] rangeOfRegex:recipient_regex];
	if (r.length >0){
		[[self textStorage] setAttributes:[[self class] attributeRedLetters] range:r];
	}
}
+(NSDictionary*)attributeRedLetters
{
	static NSMutableDictionary *dict = nil;
	if (dict ==nil){
		dict = [[NSMutableDictionary alloc] init];
		[dict setObject:[NSFont fontWithName:@"Helvetica" size:12] forKey:NSFontAttributeName];
		[dict setObject:[NSColor redColor] forKey:NSForegroundColorAttributeName];
		[dict autorelease];
		
	}
	return dict;
}
+(NSDictionary*)attributesDefault
{
	static NSMutableDictionary *dict = nil;
	if (dict ==nil){
		dict = [[NSMutableDictionary alloc] init];

		[dict setObject:[NSFont fontWithName:@"Helvetica" size:12] forKey:NSFontAttributeName];
		[dict setObject:[NSColor colorWithCalibratedRed:fontColor green:fontColor blue:fontColor alpha:1] forKey:NSForegroundColorAttributeName];
	//	
		[dict autorelease];
	}
	return dict;
}
- (void)textDidChange:(NSNotification *)aNotification
{
#ifdef __DEBUG__

	//NSLog(@"notif = %@", aNotification);

#endif
//	if ([[[aNotification userInfo] allKeys] containsObject:@"NSTextMovement"] == YES){
#ifdef __DEBUG__

	NSLog(@"notif = %@", [aNotification userInfo] );

#endif
	NSNumber *number ;//=  [[aNotification userInfo] valueForKey:@"NSTextMovement"];
		if ([number intValue]==16)
		{
			if ([[self stringValue] length] > 160){
				//[AppController displayAlertWithMessageText:@"Tekst wiadomości jest za długi"];
				NSDictionary *d = [NSDictionary dictionaryWithObject:@"Tekst wiadomości jest za długi" forKey:ErrorDescription];
				NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
				[nc postNotificationName:ABL_ErrorMessageNotification object:self userInfo:d];
				
			}
			else {
				NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
				[nc postNotificationName:ABL_SendMessageNotification object:self];
				
				
			}
		}
	//}
}
-(NSString*)stringValue
{
	return [[self textStorage] string];
}
-(void)setStringValue:(NSString*)value
{
	[[self textStorage] setAttributedString:[[NSAttributedString alloc] initWithString: value]];
	[[self textStorage] setAttributes:[MessageTextField attributesDefault] range:NSMakeRange(0,  [[self stringValue] length])];
}

#pragma mark Dragging Destination

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
{

/*	if ([self currentEditor]) {
#ifdef __DEBUG__

		NSLog(@"abort editing");

#endif
		[self abortEditing];
	}
*/	//[self performClick:nil];
	[self setNeedsDisplay:YES];
	/* if ([sender draggingSource] == self) {
        return NSDragOperationNone;
    }*/

    return NSDragOperationCopy;
}
- (void)draggingExited:(id <NSDraggingInfo>)sender
{

	//[self performClick:self]; 
}

- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
{
	return NSDragOperationCopy;
}
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
    return YES;
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{

	NSPasteboard *pb = [sender draggingPasteboard];
	@try
	{
		if ( [[pb types] containsObject:NSFilenamesPboardType] ) {
			

			NSArray *files = [pb propertyListForType:NSFilenamesPboardType];
			if ([files count]>0){
				// Perform operation using the list of files
				NSString *fileName = [[files objectAtIndex:0 ]copy];
				
				[self setDraggedImagePath:fileName ];
				if ([draggedImagePath isEqualToString:@""] ==NO){						
					[self setNeedsDisplay:YES];
					return YES;
				}
				
				
			}
		} else if ( [[pb types] containsObject:NSPICTPboardType] ) {
			
			//[self setDraggedImagePath:IMAGE_PASTED_NAME];
			NSData *data = [pb dataForType:NSPICTPboardType];
			if (data){
				NSString *path = [NSString stringWithString: [[AppController appSupportDir] stringByAppendingPathComponent:IMAGE_PASTED_NAME]];
				NSImage* img = [[NSImage alloc] initWithData:data];
				data = [img TIFFRepresentation];
				[data writeToFile:path atomically:YES];
				[self setDraggedImagePath:path];
				if (img){
					[img release];
					img = nil;
				}
				//[[self attView] setImageData:data];
			} else {
				[self setDraggedImagePath:@""];
				return NO;
			}
			return YES;
		} else if ( [[pb types] containsObject:NSStringPboardType] ) {
			NSData *data = [pb dataForType:NSStringPboardType];
			if (data){
				[self setStringValue:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
			} else
				return NO;
			return YES;
		} 
		

	}
	@catch ( NSException *e ) {
		return NO;
	}
	return NO;
}

- (void)concludeDragOperation:(id <NSDraggingInfo>)sender
{
#ifdef __DEBUG__

  NSLog(@"concludeDragOperation:");

#endif
	//[self performClick:self];

}

- (void)drawRect:(NSRect)rect
{	
	NSColor *bgColor ;
	NSRect bgRect = [self bounds] ;
    int minX = NSMinX(bgRect);
    int midX = NSMidX(bgRect);
    int maxX = NSMaxX(bgRect);
    int minY = NSMinY(bgRect);
    int midY = NSMidY(bgRect);
    int maxY = NSMaxY(bgRect);
    float radius = 10;
    NSBezierPath *bgPath = [NSBezierPath bezierPath];
	
    // Bottom edge and bottom-right curve
    [bgPath moveToPoint:NSMakePoint(midX, minY)];
    [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(maxX, minY) 
                                     toPoint:NSMakePoint(maxX, midY) 
                                      radius:radius];
    
    // Right edge and top-right curve
    [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(maxX, maxY) 
                                     toPoint:NSMakePoint(midX, maxY) 
                                      radius:radius];
    
    // Top edge and top-left curve
    [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(minX, maxY) 
                                     toPoint:NSMakePoint(minX, midY) 
                                      radius:radius];
    
    // Left edge and bottom-left curve
    [bgPath appendBezierPathWithArcFromPoint:bgRect.origin 
                                     toPoint:NSMakePoint(midX, minY) 
                                      radius:radius];
    [bgPath closePath];
	bgColor = [NSColor whiteColor];
    [bgColor set];
    [bgPath fill];
	bgPath = [NSBezierPath bezierPath];
	
    // Bottom edge and bottom-right curve
	float offset = 0.5;
	[bgPath setLineWidth:1.0];
	//bgColor = [NSColor whiteColor];
    [bgPath moveToPoint:NSMakePoint(midX, minY+offset)];
    [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(maxX-offset, minY+offset) 
                                     toPoint:NSMakePoint(maxX-offset, midY) 
                                      radius:radius];
    
    // Right edge and top-right curve
    [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(maxX-offset, maxY-offset) 
                                     toPoint:NSMakePoint(midX, maxY-offset) 
                                      radius:radius];
    
    // Top edge and top-left curve
    [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(minX+offset, maxY-offset) 
                                     toPoint:NSMakePoint(minX+offset, midY) 
                                      radius:radius];
    
    // Left edge and bottom-left curve
    [bgPath appendBezierPathWithArcFromPoint:NSMakePoint(minX+offset, minY+offset)
                                     toPoint:NSMakePoint(midX, minY+offset) 
                                      radius:radius];
    [bgPath closePath];
	bgColor = [NSColor colorWithCalibratedRed:borderColor green:borderColor blue:borderColor alpha:1];
    [bgColor set];
  [bgPath stroke];
	[super drawRect:rect];
		
}


@end
